from socket import *
from multiprocessing import Process
import signal
class TcpServer:
    def __init__(self,ip="127.0.0.1",port=1345):
        self.__socket=socket(AF_INET,SOCK_STREAM)
        self.__socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
        self.ip=ip
        self.port=port
        self.__socket.bind((ip,port))
        self.__socket.listen(15)

    __conn=None
    def deal_request(self,conn):
        # self.__socket.close()
        while True:
            data_from_client=conn.recv(1024)
            print(data_from_client.decode())
            if not data_from_client:
                break
            conn.send(b"welcome")
        conn.close()

    def main(self):
        # 处理僵尸进程
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        while True:
            print("waiting for connection...")
            try:
                TcpServer.__conn,addr=self.__socket.accept()
                print("connection from",addr)
            except KeyboardInterrupt:
                pass
                # os._exit(0)
            except Exception as e:
                print(e)
                continue
            P=Process(target=self.deal_request,args=(TcpServer.__conn,))
            P.daemon=True
            P.start()




if __name__=="__main__":
    tcp_server=TcpServer()
    tcp_server.main()